<?php

namespace App\ModelsHuayi;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\ServerException;
use GuzzleHttp\Psr7\Request;

class HuayiBasic
{
    protected $huayiConfig;

    public $defaultVersion, $httpClient;
    public $authName, $authPassword;
    public $clientId;

    public function __construct($huayi_config, $client_id = null)
    {
        $this->clientId    = $client_id;
        $this->huayiConfig = $huayi_config;

        $this->httpClient = $this->getHttpClient();
        $this->switchAuthorizationRobot();

    }

    public function switchAuthorizationRobot()
    {
        $this->authName     = $this->huayiConfig['auth_name'];
        $this->authPassword = $this->huayiConfig['auth_password'];
    }

    public function switchAuthorizationPopmart()
    {
        $this->authName     = $this->huayiConfig['auth_name1'];
        $this->authPassword = $this->huayiConfig['auth_password1'];
    }

    public function switchAuthorizationPopmart03()
    {
        $this->authName     = $this->huayiConfig['auth_name2'];
        $this->authPassword = $this->huayiConfig['auth_password2'];
    }

    public function getHttpClient()
    {
        return new Client(
            [
                'base_uri'    => $this->huayiConfig['api_url'],
                'timeout'     => 600,
                'verify'      => false,
                'http_errors' => true,
            ]
        );
    }

    /**
     * 获取执行工作的请求
     *
     * @param string $method
     * @param string $url
     * @param array $params
     * @param array $options
     * @return \GuzzleHttp\Psr7\Request
     */
    public function getRequest($method, $api, $params = [], $options = [])
    {
        $timestamp = time();

        ksort($params);
        $sign   = $this->getSign($params, $timestamp);
        $params = $params ? json_encode($params) : '{}';

        $url = '/api' . ($options['version'] ?? '/v2') . "/?auth_name={$this->authName}&api={$api}&sign={$sign}&timestamp={$timestamp}&params={$params}";
        $this->clientId && $url .= '&client_id=' . $this->clientId;

        $headers = $this->defaultHeader($options);

        return new Request($method, $url, $headers, $params);
    }

    /**
     * 执行具体操作
     *
     * @param string $method
     * @param string $url
     * @param array $params
     * @param array $options
     * @return void
     */
    public function execute($method, $api, $params = [], $options = [])
    {
        try {
            $request  = $this->getRequest($method, $api, $params, $options);
            $response = $this->httpClient->send($request);
        } catch (ServerException $e) {
            $response = $e->getResponse();
        }

        return json_decode($response->getBody(), true);
    }

    /**
     * 设置请求的默认请求头
     *
     * @param array $options
     * @return array
     */
    public function defaultHeader($options = [])
    {
        $default_headers = [
            'Content-Type' => 'application/json',
        ];

        $options_headers = $options['headers'] ?? [];

        return array_merge($default_headers, $options_headers);
    }

    public function getSign($params, $timestamp)
    {
        $string = strtoupper(MD5($this->authPassword . $timestamp));
        foreach ($params as $key => $value) {
            $string .= $key . '=' . $value . ',';
        }
        $params && $string = substr($string, 0, -1);

        return strtoupper(MD5($string));
    }
}
